<template>
  <a-modal v-model="visiable" :width="1200" @ok="setTlement" @cancel="handleCancel" footer="">
    <div style="margin-top: 20px;">
      <a-tabs :activeKey="current" @change="tabChange">
        <a-tab-pane :key="index" :tab="item.companyName" v-for="(item, index) in tabList"></a-tab-pane>
      </a-tabs>
    </div>
    <p style="font-size: 16px; font-weight: bold">
      总账户{{ countInfo.all }}元，结算{{ countInfo.settled }}元，剩余{{ countInfo.unsettled }}元
    </p>
    <a-table ref="table" size="middle" :scroll="{ x: true }" :border="false" rowKey="id" :columns="columns"
      :dataSource="dataSource" :pagination="ipagination" :loading="loading"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" class="j-table-force-nowrap"
      @change="handleTableChange">
      <template slot="htmlSlot" slot-scope="text">
        <div v-html="text"></div>
      </template>
      <template slot="imgSlot" slot-scope="text, record">
        <span v-if="!text" style="font-size: 12px; font-style: italic">无图片</span>
        <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt=""
          style="max-width: 80px; font-size: 12px; font-style: italic" />
      </template>
      <template slot="fileSlot" slot-scope="text">
        <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
        <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
          下载
        </a-button>
      </template>
      <!-- <template slot="moneySlot" slot-scope="text, record">
        <a-input v-model="record.settlementAmount" />
      </template> -->
    </a-table>
    <div v-show="loadingFlag"
      style="width: 100vw;height: 100vh;background-color: rgba(0,0,0,0.5);display: flex;justify-content: center;align-items: center;position: fixed;left: 0;top: 0;z-index: 9999999;">
      <a-spin tip="正在查询数据，请稍后..." size="large" />
    </div>
    <div class="control">
      <a-button @click="handleCancel">取消</a-button>
      <a-button @click="setTlement('self')" type="primary">手动结算</a-button>
      <a-button @click="setTlement('auto')" type="primary">自动结算</a-button>
    </div>
  </a-modal>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction } from '@/api/manage'
import { postAction } from '../../../api/manage'
export default {
  mixins: [JeecgListMixin, mixinDevice],
  data() {
    return {
      visiable: false,
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '日期',
          align: 'center',
          dataIndex: 'settlementDate',
        },
        {
          title: '结算状态',
          align: 'center',
          dataIndex: 'type',
        },
        {
          title: '金额',
          align: 'center',
          dataIndex: 'settlementAmount',
          // scopedSlots: { customRender: 'moneySlot' },
        },
      ],
      url: {
        // list: '/hc/hcMerchantSettlement/queryListById',
        list: '/hc/hcMerchantSettlement/queryListByIdNew',
        delete: '/hc/hcMerchantSettlement/delete',
        deleteBatch: '/hc/hcMerchantSettlement/deleteBatch',
        exportXlsUrl: '/hc/hcMerchantSettlement/exportXls',
        importExcelUrl: 'hc/hcMerchantSettlement/importExcel',
      },
      queryParam: {},
      merchantOpenId: '', //商家的openId
      countInfo: {},
      loadingFlag: false,

      tabList: [{ companyName: '用户账户' }],
      current: 0
    }
  },
  mounted() {
  },
  methods: {
    show(record) {
      this.visiable = true
      this.queryParam.merchantId = record.id
      this.merchantOpenId = record.merchantOpenId;
      this.searchQuery();
      this.getInfo();
      this.getCompanyList();
    },
    //获取所有公司列表
    async getCompanyList() {
      let res = await getAction('/hc/hcCompanyMerchantInfo/queryCompanyListByMerchantId', { pageSize: 999999, pageNo: 1, merchantId: this.queryParam.merchantId });
      console.log('公司res', res);
      this.tabList = [...this.tabList, ...res.result];
    },

    async getInfo() {
      let res;
      if (this.current === 0) {
        res = await getAction('hc/hcMerchantSettlement/querySumByIdNew', { merchantId: this.queryParam.merchantId })
      } else {
        res = await getAction('/hc/hcCompanyMerchantSettlement/querySumByMerchantIdAndCompanyId', { merchantId: this.queryParam.merchantId, companyId: this.queryParam.companyId })
      }
      this.countInfo = {
        all: res.result.all,
        settled: 0,
        unsettled: res.result.all,
      }
    },
    async setTlement(type) {
      if (type == 'auto' && !this.merchantOpenId) {
        this.$message.warning('系统还没有获取到该商家的openId,暂时无法使用自动结算功能');
        return;
      }
      let flag = false;
      for (let i = 0; i < this.selectionRows.length; i++) {
        let type = this.selectionRows[i].type;
        if (type == '正在结算') {
          flag = true;
          break;
        }
      }
      if (flag) {
        this.$message.warning('您选中的数据中存在正在结算的记录，请取消勾选后再次提交');
        return;
      }
      if (this.selectionRows.length == 0) {
        this.$message.warning('请先选择数据');
        return;
      }
      this.loadingFlag = true;
      let url;
      if(this.current==0){
        url = type == 'self' ? 'hc/hcMerchantSettlement/doSettlement' : 'hc/hcMerchantSettlement/doSettlementNew'
      }else{
        url = type == 'self' ? '/hc/hcCompanyMerchantSettlement/doSettlement' : '/hc/hcCompanyMerchantSettlement/doSettlementNew'
      }
      let res = await postAction(url, this.selectionRows)
      this.loadingFlag = false;
      if (res.success) {
        this.$message.success('结算成功')
        this.visiable = false
        this.$emit('loadData')
      } else {
        this.$message.warning(res.message)
      }
    },
    handleCancel() { this.visiable = false; this.tabList = [{ companyName: '用户账户' }];this.current==0 },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;

      let total = 0
      this.selectionRows.forEach((item) => {
        // total = total + item.settlementAmount
        total = this.accAdd(total, item.settlementAmount)
      })
      this.countInfo.settled = total
      this.countInfo.unsettled = this.countInfo.all - total;
      console.log('total', total, 'countInfo', this.countInfo)
    },
    //加法
    accAdd(arg1, arg2) {
      var r1, r2, m, c;
      try {
        r1 = arg1.toString().split(".")[1].length;
      } catch (e) {
        r1 = 0;
      }
      try {
        r2 = arg2.toString().split(".")[1].length;
      } catch (e) {
        r2 = 0;
      }
      c = Math.abs(r1 - r2);
      m = Math.pow(10, Math.max(r1, r2));
      if (c > 0) {
        var cm = Math.pow(10, c);
        if (r1 > r2) {
          arg1 = Number(arg1.toString().replace(".", ""));
          arg2 = Number(arg2.toString().replace(".", "")) * cm;
        } else {
          arg1 = Number(arg1.toString().replace(".", "")) * cm;
          arg2 = Number(arg2.toString().replace(".", ""));
        }
      } else {
        arg1 = Number(arg1.toString().replace(".", ""));
        arg2 = Number(arg2.toString().replace(".", ""));
      }
      return (arg1 + arg2) / m;
    },

    tabChange(e) {
      console.log('e', e);
      this.current = e;
      if (e === 0) {
        this.url.list = '/hc/hcMerchantSettlement/queryListByIdNew'
        this.queryParam.companyId = null
      } else {
        this.url.list = '/hc/hcCompanyMerchantSettlement/queryListByMerchantIdAndCompanyId'
        this.queryParam.companyId = this.tabList[e].id;
      }
      this.loadData();
      this.getInfo();
    }
  },
}
</script>

<style scoped lang="scss">
.control {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 20px 0 0 0;
  margin-top: 20px;
  border-top: 1px solid #eee;

  >button {
    margin-left: 20px;
  }
}
</style>